package com.micro.common.service.orm.service;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.micro.framework.starter.web.converter.IDictConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class DictConverterImpl implements IDictConverter {
    @Resource
    private DictDataServiceImpl dictDataService;
    //redis 缓存
    @Resource
    private RedisTemplate<String, Map<String, String>> redisTemplate;

    // Caffeine 本地缓存，效率高
    private Cache<String, Map<String, String>> cache = Caffeine.newBuilder()
            .initialCapacity(50)
            .maximumSize(300)
            .expireAfterWrite(10, TimeUnit.MINUTES)
            .build();

    @Value("${dict.converter.expireMinute:10}")
    private int expireMinute;

    public String convertTo(String source, String dictGroup) {
        Map<String, String> map = null;
        String dictKey = "dictConverter:" + dictGroup;
        long start = System.currentTimeMillis();
        map = cache.getIfPresent(dictKey);
        if (MapUtils.isEmpty(map)) {
            map = redisTemplate.opsForValue().get(dictKey);
            if (MapUtils.isEmpty(map)) {
                 map = dictDataService.dictMap(dictGroup);
                 redisTemplate.opsForValue().set(dictKey, map, expireMinute, TimeUnit.MINUTES);
            }
            cache.put(dictKey, map);
        }
        log.info("DictConverter convertTo times {} ms", (System.currentTimeMillis() - start));
        if (MapUtils.isNotEmpty(map)) {
            return map.get(source);
        }
        return null;
    }
}
